<template>
  <div class="flex h-full">
    <!-- 联系人列表区域 -->
    <div class="w-80 bg-white border-r border-gray-100 flex flex-col">
      <!-- 顶部搜索和添加区域 -->
      <div class="p-4 border-b border-gray-200">
        <div class="flex items-center gap-2">
          <!-- 搜索框 -->
          <div class="relative flex-1">
            <input v-model="searchQuery" type="text" placeholder="搜索联系人"
              class="w-full pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:border-blue-500"
              @input="handleSearch" />
            <span class="absolute left-3 top-2.5 text-gray-400">
              <el-icon>
                <Search />
              </el-icon>
            </span>
          </div>
          <!-- 添加好友按钮 -->
          <el-button type="primary" circle class="flex-shrink-0" @click="handleAddFriend">
            <el-icon>
              <Plus />
            </el-icon>
          </el-button>
        </div>
      </div>

      <!-- 新的朋友选项 -->
      <div class="p-2 border-b border-gray-200">
        <div class="flex items-center p-2 rounded-lg hover:bg-gray-100 cursor-pointer" @click="handleNewFriends">
          <el-avatar :size="40" class="bg-blue-500">
            <el-icon :size="20">
              <UserFilled />
            </el-icon>
          </el-avatar>
          <span class="ml-3 text-gray-900">新的朋友</span>
          <el-badge v-if="contactStore.unreadCount > 0" :value="contactStore.unreadCount" class="ml-auto" />
        </div>
      </div>

      <ContactList :filter-query="searchQuery" />
    </div>

    <!-- 用户详情区域 -->
    <div class="flex-1 bg-white">
      <router-view></router-view>
    </div>
  </div>

  <!-- 添加好友对话框 -->
  <el-dialog v-model="dialogVisible" title="添加好友" width="400px" :close-on-click-modal="false">
    <div class="mb-4">
      <el-input v-model="searchUserQuery" placeholder="请输入用户邮箱搜索" clearable :loading="searching"
        @keydown.enter="searchUser">
        <template #append>
          <el-button :loading="searching" @click="searchUser">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </template>
      </el-input>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searchResult" class="p-3 hover:bg-gray-50 rounded-lg">
      <div class="flex items-center">
        <el-avatar :size="40" :src="searchResult.avatar" />
        <div class="ml-3 flex-1">
          <div class="font-medium">{{ searchResult.nickname }}</div>
          <div class="text-sm text-gray-500">{{ searchResult.email }}</div>
        </div>
      </div>
      <!-- 好友状态/操作按钮 -->
      <div class="mt-3 flex justify-end">
        <div v-if="isCurrentUser" class="text-sm text-gray-400 italic px-3 py-1 bg-gray-50 rounded-full">
          这是你自己
        </div>
        <template v-else>
          <el-button v-if="!searchResult.isFriend" type="primary" size="small" @click="confirmAddFriend"
            :loading="sendingRequest">
            添加好友
          </el-button>
          <el-button v-else-if="searchResult.friendStatus === 0" type="info" size="small" disabled>
            请求已发送
          </el-button>
          <el-button v-else-if="searchResult.friendStatus === 1" type="success" size="small" disabled>
            已是好友
          </el-button>
          <el-button v-else-if="searchResult.friendStatus === 2" type="warning" size="small" @click="confirmAddFriend"
            :loading="sendingRequest">
            已被拒绝，重新申请
          </el-button>
          <el-button v-else-if="searchResult.friendStatus === 3" type="danger" size="small" disabled>
            已被拉黑
          </el-button>
        </template>
      </div>
    </div>

    <!-- 无搜索结果提示 -->
    <div v-else-if="hasSearched" class="flex flex-col items-center justify-center py-8 text-gray-500">
      <el-icon :size="48" class="mb-4">
        <User />
      </el-icon>
      <p>未找到相关用户</p>
    </div>

    <template #footer>
      <div class="flex justify-end">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Plus, User, UserFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import ContactList from '@/components/contacts/ContactList.vue'
import { searchUsers } from '@/api/user'
import { sendFriendRequest } from '@/api/contact'
import type { UserSearchResult } from '@/types'
import { useUserStore } from '@/stores/useUserStore'
import { useContactStore } from '@/stores/useContactStore'

const router = useRouter()
const userStore = useUserStore()
const contactStore = useContactStore()

// 处理新朋友点击事件
const handleNewFriends = () => {
  router.push('/contacts/new-friends')
  // 重置未读数量
  contactStore.unreadCount = 0
}

// 搜索联系人
const searchQuery = ref('')
const handleSearch = () => {
  // 搜索逻辑会通过props传递到ContactList组件中处理
}

// 添加好友相关
const dialogVisible = ref(false)
const searchUserQuery = ref('')
const hasSearched = ref(false)
const searching = ref(false)
const searchResult = ref<UserSearchResult | null>(null)
const sendingRequest = ref(false)

// 打开添加好友对话框
const handleAddFriend = () => {
  dialogVisible.value = true
  searchUserQuery.value = ''
  searchResult.value = null
  hasSearched.value = false
}

// 搜索用户
const searchUser = async () => {
  const email = searchUserQuery.value.trim()
  if (!email) {
    ElMessage.warning('请输入邮箱')
    return
  }

  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(email)) {
    ElMessage.warning('请输入正确的邮箱格式')
    return
  }

  searching.value = true
  try {
    const res = await searchUsers(email)
    searchResult.value = res.data
    hasSearched.value = true
  } catch (error: any) {
    ElMessage.error(error.message || '搜索用户失败')
    searchResult.value = null
  } finally {
    searching.value = false
  }
}

// 确认添加好友
const confirmAddFriend = async () => {
  if (!searchResult.value || sendingRequest.value) return

  try {
    sendingRequest.value = true
    await sendFriendRequest({
      friendId: searchResult.value.id
    })
    ElMessage.success('好友请求已发送')
    // 更新搜索结果中的好友状态
    if (searchResult.value) {
      searchResult.value.friendStatus = 0 // 设置为待确认状态
      searchResult.value.isFriend = true
    }
    dialogVisible.value = false
  } catch (error: any) {
    ElMessage.error(error.message || '发送好友请求失败')
  } finally {
    sendingRequest.value = false
  }
}

const isCurrentUser = computed(() => {
  return searchResult.value?.id === userStore.userInfo?.id
})
</script>